package org.zsqx.tools;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import org.zsqx.bean.DisasterUpload;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class FreemarkTools {
	
	public String buildXml(String ftlPath,DisasterUpload disaster) throws IOException, TemplateException{
		Configuration cfg = new Configuration();
		cfg.setDirectoryForTemplateLoading(new File(ftlPath));
		cfg.setObjectWrapper(new DefaultObjectWrapper());
		Template temp = cfg.getTemplate("disaster.ftl");
		//如果为空，自动换成空字符串
		cfg.setClassicCompatible(true);
		//xml文件命名规则12345站号1无2010年12月29日10时11分07秒
		Calendar c = Calendar.getInstance();
		String fileName = null;
		if(disaster.getInfosources().equals("月报")){
			fileName = disaster.getStationid()+"0"+c.get(Calendar.YEAR);
			
			fileName += (c.get(Calendar.MONTH)+1)+".xml";
			
		}else{
		 fileName = disaster.getStationid()+"0"+c.get(Calendar.YEAR)+(c.get(Calendar.MONTH)+1)+c.get(Calendar.DAY_OF_MONTH)
					+c.get(Calendar.HOUR_OF_DAY)+c.get(Calendar.MINUTE)+c.get(Calendar.SECOND)+".xml";
		}
		PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(ftlPath+"xmlTemplete/"+fileName)));
		Map<String,Object> tmpValue = new HashMap<String,Object>();
		tmpValue.put("disaster", disaster);
//		Date date = new Date();
//		tmpValue.put("date", date);
		temp.process(tmpValue, out);
		out.flush();
		System.out.println("fileName:"+fileName);
		return fileName;
	}
	public String getDate(){
		Calendar c = Calendar.getInstance();
		String month = String.valueOf(c.get(Calendar.MONTH)+1);
		if(Integer.parseInt(month)<10){
			month = "0"+month;
		}
		String day = String.valueOf(c.get(Calendar.DAY_OF_MONTH));
		if(Integer.parseInt(day)<10){
			day = "0"+day;
		}
		String hour = String.valueOf(c.get(Calendar.HOUR_OF_DAY));
		if(Integer.parseInt(hour)<10){
			hour = "0"+hour; 
		}
		String minute = String.valueOf(c.get(Calendar.MINUTE));
		if(Integer.parseInt(minute)<10){
			minute = "0"+minute; 
		}
		String second = String.valueOf(c.get(Calendar.SECOND));
		if(Integer.parseInt(second)<10){
			second = "0"+second; 
		}
		return c.get(Calendar.YEAR)+month+day+hour+minute+second;
	}
	
	public static void main(String[] args) throws IOException, TemplateException {
		FreemarkTools f = new FreemarkTools();
		String name = f.buildXml("C:\\Users\\lenovo\\Workspaces\\MyEclipse 8.5\\zsqx\\WebRoot\\login\\flt/", new DisasterUpload());
		System.out.println(name);
	}
	
}
